#include "mqsamplemessagehandler.h"
#include <QDateTime>
#include <QJsonDocument>
#include <QJsonObject>
#include <QThread>
#include "mqclient.h"

MQSampleMessageHandler::MQSampleMessageHandler(const QString& handlerName, 
                                             QObject *parent)
    : QObject(parent)
    , m_handlerName(handlerName)
    , m_verboseLogging(true)//GJ 关闭MQSampleMessageHandler的  log打印
    , m_processedCount(0)
    , m_successCount(0)
    , m_failureCount(0)
{
    qDebug() << "MQSampleMessageHandler::MQSampleMessageHandler() - Created handler:" 
             << m_handlerName;
    
    // 初始化协议配置
    if (!m_protocolConfig.loadConfig()) {
        qWarning() << "MQSampleMessageHandler::MQSampleMessageHandler() - Failed to load protocol config";
    }
}

bool MQSampleMessageHandler::handleMessage(const QString& exchange, 
                                          const QString& routingKey, 
                                          const QByteArray& data)
{
    qint64 startTime = QDateTime::currentMSecsSinceEpoch();

    QJsonObject requestData;
    QString errorMsg;
    QJsonObject errorResponse;
    QJsonObject successResponse;
    bool success;

    m_processedCount++;
        
//        if (m_verboseLogging) {
//            qDebug() << "MQSampleMessageHandler::handleMessage() - Processing message"
//                     << "Handler:" << m_handlerName
//                     << "Exchange:" << exchange
//                     << "RoutingKey:" << routingKey
//                     << "DataSize:" << data.size()
//                     << "ThreadId:" << QThread::currentThreadId();
//        }


    if (!parseRequestJson(QString::fromUtf8(data), requestData, errorMsg)) {
        //消息不是json格式
        if (m_verboseLogging)
            qDebug() << "ERROR" + QString("消息解析失败: %1").arg(errorMsg);
        errorResponse = buildErrorResponse(requestData.value("request_id").toString(), errorMsg);
        success =false;
    }else{
        if(validateReplyRequest(requestData, errorMsg)){
            //GJ todo "消息回复" 暂时不做处理
            m_successCount++;
            success = true;
            if (m_verboseLogging)
                qDebug() << QString("消息回复, 暂时不做处理:  ") << requestData;
            return success;//暂时不做处理 直接返回true
        }else{
            if (!validateRequest(requestData, errorMsg)) {
                //json第一层字段不匹配
                if (m_verboseLogging)
                    qDebug() << "ERROR" + QString("消息验证失败: %1").arg(errorMsg);
                errorResponse = buildErrorResponse(requestData.value("request_id").toString(), errorMsg);
                success =false;
            }else{
                if(!validateDataInfoByConfigWithType(QString::number(requestData.value("function_code").toInt()), requestData["data_info"].toObject(), errorMsg)){
                    //json第二层不匹配（data_info{}） 或者 第三层不匹配（当有第三层data{}时）
                    if (m_verboseLogging)
                    qDebug() << "ERROR" + QString("消息验证失败: %1").arg(errorMsg);
                    errorResponse = buildErrorResponse(requestData.value("request_id").toString(), errorMsg);
                    success =false;
                }else {
                    // 消息处理
                    success = true;//GJ todo 暂定当消息格式正确时就为true
                    processMessageData(data, requestData);
                    //success =  processMessageData(data, requestData);
                    successResponse = buildSuccessResponse(requestData.value("request_id").toString(), QJsonObject());//GJ todo参数暂定为 QJsonObject()
                }
            }
        }
    }

    // 更新统计信息
    if (success) {
        m_successCount++;
        QByteArray data = QJsonDocument(successResponse).toJson(QJsonDocument::Compact);
        MQClient::getInstance()->publishMessageAsync(data);//mq通信，"指令下发成功"
        qDebug() << "successResponse: " << successResponse;
    } else {
        m_failureCount++;
        QByteArray data = QJsonDocument(errorResponse).toJson(QJsonDocument::Compact);
        MQClient::getInstance()->publishMessageAsync(data);//mq通信,"指令下发失败"
        qDebug() << "errorResponse: " << errorResponse;
    }

    qint64 processingTime = QDateTime::currentMSecsSinceEpoch() - startTime;

    if (m_verboseLogging) {
        qDebug() << "MQSampleMessageHandler::handleMessage() - Message processed"
                 << "Handler:" << m_handlerName
                 << "Success:" << success
                 << "ProcessingTime:" << processingTime << "ms"
                 << "Statistics: Total:" << m_processedCount
                 << "Success:" << m_successCount
                 << "Failure:" << m_failureCount;
    }

    // 发射处理完成信号
    emit messageProcessed(exchange, routingKey, success, processingTime);

    return success;
}

QString MQSampleMessageHandler::getHandlerName() const
{
    return m_handlerName;
}

void MQSampleMessageHandler::setVerboseLogging(bool enabled)
{
    m_verboseLogging = enabled;
    qDebug() << "MQSampleMessageHandler::setVerboseLogging() - Handler:" 
             << m_handlerName << "VerboseLogging:" << enabled;
}

int MQSampleMessageHandler::getProcessedMessageCount() const
{
    return m_processedCount;
}

void MQSampleMessageHandler::resetStatistics()
{
    m_processedCount = 0;
    m_successCount = 0;
    m_failureCount = 0;
    
    qDebug() << "MQSampleMessageHandler::resetStatistics() - Handler:" 
             << m_handlerName << "Statistics reset";
}

QJsonObject MQSampleMessageHandler::buildSuccessResponse(const QString& requestId, const QJsonObject& data, int type) const
{
    QJsonObject response;
    response["code"] = 99;
    if(type ==2){
         response["data"] = data;
    }
    response["info"] = "请求成功";
    response["request_id"] = requestId;
    return response;
}

QJsonObject MQSampleMessageHandler::buildErrorResponse(const QString& requestId, const QString& errorMsg, int type) const
{
    QJsonObject response;
    response["code"] = -99;
    if(type ==2){
        response["data"] = QJsonObject();
    }
    response["info"] = errorMsg.isEmpty() ? "指令下发失败" : errorMsg;
    response["request_id"] = requestId;
    return response;
}

bool MQSampleMessageHandler::parseRequestJson(const QString& requestBody, QJsonObject& jsonData, QString& errorMsg) const
{
    if (requestBody.isEmpty()) {
        errorMsg = "请求体不能为空";
        return false;
    }

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(requestBody.toUtf8(), &parseError);

    if (parseError.error != QJsonParseError::NoError) {
        errorMsg = QString("JSON解析错误: %1").arg(parseError.errorString());
        return false;
    }

    if (!doc.isObject()) {
        errorMsg = "消息数据必须是JSON对象";
        return false;
    }
//    qDebug() << "requestBody" << requestBody;
    jsonData = doc.object();
//    qDebug() << jsonData;
    return true;
}

bool MQSampleMessageHandler::validateRequest(const QJsonObject& requestData, QString& errorMsg)
{
    // 检查必要的字段
    if (!requestData.contains("function_code")) {
        errorMsg = "缺少function_code字段";
        return false;
    }

    if (!requestData.contains("data_info")) {
        errorMsg = "缺少data_info字段";
        return false;
    }

    // 检查请求ID
    if (!requestData.contains("request_id")) {
        errorMsg = "缺少request_id字段";
        return false;
    }

//    QString requestId = requestData["request_id"].toString();
//    if (requestId.isEmpty()) {
//        errorMsg = "request_id不能为空";
//        return false;
//    }
    return true;
}

bool MQSampleMessageHandler::validateReplyRequest(const QJsonObject& requestData, QString& errorMsg)
{
    if (!requestData.contains("code")) {
        errorMsg = "消息回复,缺少code字段";
        return false;
    }

    if (!requestData.contains("info")) {
        errorMsg = "消息回复,缺少info字段";
        return false;
    }

    if (!requestData.contains("request_id")) {
        errorMsg = "消息回复,缺少request_id字段";
        return false;
    }

//    emit ReceivedmessageReply(requestData["code"].toInt(), requestData["info"].toString(), requestData["request_id"].toString());
    return true;
}

bool MQSampleMessageHandler::processMessageData(const QByteArray& data, const QJsonObject& requestData)
{
    if (m_verboseLogging) {
        qDebug() << "MQSampleMessageHandler::processMessageData() - Processing JSON message"
                 << "Keys:" << requestData.keys();
    }

    // GJ todo 消费逻辑
    // 处理逻辑
    int function_code = requestData["function_code"].toInt();

    if (function_code > 100 && function_code < 200)  {
        // 处理命令消息
        return processCommonMessage(requestData);
    } else if (function_code > 200 && function_code < 300)  {
        // 处理写数据库，消息
        return processDatabaseMessage(requestData);
    } else if (function_code > 300 && function_code < 400)  {
        // 处理RXX_API消息
        return processRXX_APIMessage(requestData);
    } else {
        qWarning() << "MQSampleMessageHandler::processMessageData() - 未定义的function_code:"
                   << function_code << "  消息体："<< requestData;
        return false;
    }
}

bool MQSampleMessageHandler::processCommonMessage(const QJsonObject& obj)
{
    //GJ todo
    int function_code = obj["function_code"].toInt(); 
    switch (function_code) {
        case 101:{
           //1.处理
           break;
        }
        case 102:{
           //1.处理
           break;
        }
    }
}

bool MQSampleMessageHandler::processDatabaseMessage(const QJsonObject& obj)
{
    //GJ todo
    int function_code = obj["function_code"].toInt();
    switch (function_code) {
        case 201:{
           //1.处理
           break;
        }
        case 202:{
           //1.处理
           break;
        }
        //......
    }
}

bool MQSampleMessageHandler::processRXX_APIMessage(const QJsonObject& obj)
{
    //GJ todo
    int function_code = obj["function_code"].toInt();
    switch (function_code) {
        case 301:{
           //1.处理
           break;
        }
        case 302:{
           //1.处理
           break;
        }
        //......
    }
}

bool MQSampleMessageHandler::validateDataInfoByConfig(const QString& functionCode, 
                                                     const QJsonObject& dataInfo, 
                                                     QString& errorMsg)
{
    // 检查协议是否存在
    if (!m_protocolConfig.hasProtocol(functionCode)) {
        errorMsg = QString("未找到功能码 %1 的协议配置").arg(functionCode);
        return false;
    }
    
    // 获取必需字段列表
    QStringList requiredFields = m_protocolConfig.getRequiredFields(functionCode, "data_info");
    
    // 检查必需字段是否存在
    for (const QString& field : requiredFields) {
        if (!dataInfo.contains(field)) {
            errorMsg = QString("data_info缺少必需字段: %1").arg(field);
            return false;
        }
    }
    
    // 如果data_info包含data字段，验证嵌套的data字段
    if (dataInfo.contains("data") && dataInfo["data"].isObject()) {
        QJsonObject dataObject = dataInfo["data"].toObject();
        return validateNestedDataFields(functionCode, dataObject, errorMsg);
    }
    
    return true;
}

bool MQSampleMessageHandler::validateDataInfoByConfigWithType(const QString& functionCode, 
                                                            const QJsonObject& dataInfo, 
                                                            QString& errorMsg)
{
    // 检查协议是否存在
    if (!m_protocolConfig.hasProtocol(functionCode)) {
        errorMsg = QString("未找到功能码 %1 的协议配置").arg(functionCode);
        return false;
    }
    
    // 获取字段信息列表（包含类型）
    QList<FieldInfo> fieldInfos = m_protocolConfig.getFieldInfos(functionCode, "data_info");
    
    // 检查必需字段是否存在并验证类型
    for (const FieldInfo& fieldInfo : fieldInfos) {
        if (!dataInfo.contains(fieldInfo.name)) {
            errorMsg = QString("data_info缺少必需字段: %1").arg(fieldInfo.name);
            return false;
        }
        
        // 验证字段类型
        if (!validateFieldType(fieldInfo.name, dataInfo[fieldInfo.name], fieldInfo.type, errorMsg)) {
            return false;
        }
    }
    
    // 如果data_info包含data字段，验证嵌套的data字段
    if (dataInfo.contains("data") && dataInfo["data"].isObject()) {
        QJsonObject dataObject = dataInfo["data"].toObject();
        return validateNestedDataFieldsWithType(functionCode, dataObject, errorMsg);
    }
    
    return true;
}

bool MQSampleMessageHandler::validateNestedDataFields(const QString& functionCode, 
                                                     const QJsonObject& dataObject, 
                                                     QString& errorMsg)
{
    // 获取data字段的必需字段列表
    QStringList requiredDataFields = m_protocolConfig.getRequiredFields(functionCode, "data");
    
    // 检查必需字段是否存在
    for (const QString& field : requiredDataFields) {
        if (!dataObject.contains(field)) {
            errorMsg = QString("data字段缺少必需字段: %1").arg(field);
            return false;
        }
    }
    
    return true;
}

bool MQSampleMessageHandler::validateNestedDataFieldsWithType(const QString& functionCode, 
                                                            const QJsonObject& dataObject, 
                                                            QString& errorMsg)
{
    // 获取data字段的字段信息列表（包含类型）
    QList<FieldInfo> dataFieldInfos = m_protocolConfig.getFieldInfos(functionCode, "data");
    
    // 检查必需字段是否存在并验证类型
    for (const FieldInfo& fieldInfo : dataFieldInfos) {
        if (!dataObject.contains(fieldInfo.name)) {
            errorMsg = QString("data字段缺少必需字段: %1").arg(fieldInfo.name);
            return false;
        }
        
        // 验证字段类型
        if (!validateFieldType(fieldInfo.name, dataObject[fieldInfo.name], fieldInfo.type, errorMsg)) {
            return false;
        }
    }
    
    return true;
}

bool MQSampleMessageHandler::validateFieldType(const QString& fieldName, 
                                              const QJsonValue& fieldValue, 
                                              const QString& expectedType, 
                                              QString& errorMsg)
{
    if (expectedType == "string") {
        if (!fieldValue.isString()) {
            errorMsg = QString("字段 %1 应为字符串类型，实际类型: %2")
                      .arg(fieldName)
                      .arg(fieldValue.type() == QJsonValue::Null ? "null" : 
                           fieldValue.type() == QJsonValue::Bool ? "bool" :
                           fieldValue.type() == QJsonValue::Double ? "number" :
                           fieldValue.type() == QJsonValue::Array ? "array" :
                           fieldValue.type() == QJsonValue::Object ? "object" : "unknown");
            return false;
        }
    }
    else if (expectedType == "double" || expectedType == "number") {
        if (!fieldValue.isDouble()) {
            errorMsg = QString("字段 %1 应为数值类型，实际类型: %2")
                      .arg(fieldName)
                      .arg(fieldValue.type() == QJsonValue::Null ? "null" : 
                           fieldValue.type() == QJsonValue::Bool ? "bool" :
                           fieldValue.type() == QJsonValue::String ? "string" :
                           fieldValue.type() == QJsonValue::Array ? "array" :
                           fieldValue.type() == QJsonValue::Object ? "object" : "unknown");
            return false;
        }
    }
    else if (expectedType == "bool" || expectedType == "boolean") {
        if (!fieldValue.isBool()) {
            errorMsg = QString("字段 %1 应为布尔类型，实际类型: %2")
                      .arg(fieldName)
                      .arg(fieldValue.type() == QJsonValue::Null ? "null" : 
                           fieldValue.type() == QJsonValue::Double ? "number" :
                           fieldValue.type() == QJsonValue::String ? "string" :
                           fieldValue.type() == QJsonValue::Array ? "array" :
                           fieldValue.type() == QJsonValue::Object ? "object" : "unknown");
            return false;
        }
    }
    else if (expectedType == "object") {
        if (!fieldValue.isObject()) {
            errorMsg = QString("字段 %1 应为对象类型，实际类型: %2")
                      .arg(fieldName)
                      .arg(fieldValue.type() == QJsonValue::Null ? "null" : 
                           fieldValue.type() == QJsonValue::Bool ? "bool" :
                           fieldValue.type() == QJsonValue::Double ? "number" :
                           fieldValue.type() == QJsonValue::String ? "string" :
                           fieldValue.type() == QJsonValue::Array ? "array" : "unknown");
            return false;
        }
    }
    else if (expectedType == "array") {
        if (!fieldValue.isArray()) {
            errorMsg = QString("字段 %1 应为数组类型，实际类型: %2")
                      .arg(fieldName)
                      .arg(fieldValue.type() == QJsonValue::Null ? "null" : 
                           fieldValue.type() == QJsonValue::Bool ? "bool" :
                           fieldValue.type() == QJsonValue::Double ? "number" :
                           fieldValue.type() == QJsonValue::String ? "string" :
                           fieldValue.type() == QJsonValue::Object ? "object" : "unknown");
            return false;
        }
    }
    // 如果类型不在已知类型列表中，跳过类型检查
    
    return true;
}
